<template>
  <div class="search_container">
    <!-- 搜索栏 -->
    <!--
      Tips: 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮
     -->
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- /搜索栏 -->

    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :searchText="searchText" />
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion
      v-else-if="searchText"
      :searchText="searchText"
      @search="onSearch"
    />
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history
      v-else
      :searchHistories="searchHistories"
      @clear-search-histories="searchHistories = []"
      @search="onSearch"
    />
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import SearchHistory from './components/search-history';
import SearchSuggestion from './components/search-suggestion';
import SearchResult from './components/search-result';
import { setItem, getItem } from '@/assets/utils/storage';

export default {
  name: 'SearchIndex',
  data() {
    return {
      // 搜索框输入的内容
      searchText: '',
      // 控制搜索结果的展示
      isResultShow: false,
      // 搜索历史记录
      searchHistories: getItem('TOUTIAO_SEARCH_HISTORIES') || []
    };
  },
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  created: function() {},
  methods: {
    onSearch(val) {
      // 更新文本框内容
      this.searchText = val;

      // 存储搜索历史记录
      // 要求：不要有重复历史记录、最新的排在最前面
      // indexOf()方法返回在数组中可以找到一个给定元素的第一个索引，如果不存在，则返回-1。
      const index = this.searchHistories.indexOf(this.searchText);
      if (index === -1) {
        this.searchHistories.push(this.searchText);
      } else {
        this.searchHistories.splice(index, 1);
        this.searchHistories.push(this.searchText);
      }

      // 渲染搜索结果
      this.isResultShow = true;
    },
    onCancel() {
      this.$router.back();
    }
  },
  watch: {
    /**
     * 监听搜索历史的变化
     */
    searchHistories(value) {
      setItem('TOUTIAO_SEARCH_HISTORIES', value);
    }
  }
};
</script>

<style scoped lang="less">
.search_container {
  .van-search__action {
    color: white;
  }
}
</style>
